﻿using System.Windows.Controls;

namespace ScrollerMusicPlayerUI.Controls.Primitives
{
    public class FillManager
    {
        private BetterWarpPanel _panel;
        private BlockInfo[] _blockInfos;
        private int _loopIndex;

        public FillManager(BetterWarpPanel panel, BlockInfo[] blockInfos)
        {
            _panel = panel;
            _blockInfos = blockInfos;
        }

        public void Fill()
        {
            _panel.Children.Clear();
            if (_panel.IsLoaded == false) return;
            if (_panel.BlockInfos == null) return;
            if (_panel.BlockInfos.Length == 0) return;

            //foreach (var blockInfo in _panel.BlockInfos)
            //{
            //    var uiElem = CreateUIElement(blockInfo);
            //    _panel.Children.Add(uiElem);
            //}

            var height = _panel.ActualHeight;
            var unitSize = _panel.ActualWidth / _panel.Columns;
            var rowCount = (int)Math.Ceiling(height / unitSize)+1;

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < _panel.Columns; j++)
                {
                    var blockInfo = GetNextBlockInfo();
                    var uiElem = CreateUIElement(blockInfo);
                    _panel.Children.Add(uiElem);
                }
            }

        }

        public void ContinueFill()
        {
            if (_panel.IsLoaded == false) return;
            if (_panel.BlockInfos == null) return;
            if (_panel.BlockInfos.Length == 0) return;

            var oldCount = _panel.Children.Count;
            var height = _panel.ActualHeight;
            var unitSize = _panel.ActualWidth / _panel.Columns;
            var rowCount = (int)Math.Ceiling(height / unitSize)+1;
            var totalCount = rowCount * _panel.Columns;

            if (oldCount >= totalCount) return;

            for (int i = oldCount; i < totalCount; i++)
            {
                //var rid = i / _panel.Columns;
                //var cid = i % _panel.Columns;
                var blockInfo = GetNextBlockInfo();
                var uiElem = CreateUIElement(blockInfo);
                _panel.Children.Add(uiElem);
            }

        }

        private Border CreateUIElement(BlockInfo info)
        {
            var border = new Border() { Background = info.Brush };
            return border;
        }

        private BlockInfo GetNextBlockInfo()
        {
            var blockInfo = _blockInfos[_loopIndex];
            _loopIndex = (_loopIndex + 1) % _blockInfos.Length;
            return blockInfo;
        }
    }
}
